<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('article.articleInfo')"
    width="1200"
    @close="onDialogClose"
    :destroy-on-close="true"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formEdit"
      :rules="rules"
      label-position="top"
      label-width="120px"
    >
      <el-container>
        <!-- fix el-affix 在 el-dialog\el-row 中无效，滚动时 toolbar 移动到这里，还原时 toolbar 复位 -->
        <el-affix
          id="affix-container"
          style="position: absolute; z-index: 1400; margin-left: 20px"
          :offset="0"
          @scroll="handleAffixScroll"
        >
        </el-affix>
        <el-main style="padding-top: 0px">
          <el-row>
            <el-col>
              <el-form-item :label="t('article.title')" prop="title">
                <el-input
                  v-model="formEdit.title"
                  maxlength="128"
                  :placeholder="t('article.title')"
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <div class="ck-body-wrapper">
              <!-- fix 在弹出窗口中 link 之类的 pop 弹出无效问题 -->
              <!-- https://devs.keenthemes.com/question/ck-editor-5-link-url-not-focussing-when-inside-modal -->
              <div id="affix-reset-container" style="">
                <div
                  id="toolbar-container"
                  style="width: 768px; background-color: #fff"
                ></div>
              </div>
              <div id="editor" v-loading="true"></div>
              <br />
              <el-upload
                ref="logoFileRef"
                v-model:file-list="logoFileList"
                accept=".doc, .docx, .xls, .xlsx, .pdf, .zip, .rar"
                :action="apiUpload.uploadUrl()"
                :headers="headers()"
                :data="{
                  businessKey: formEdit.articleId,
                  category: logoFileCategory,
                }"
                :limit="5"
                :on-preview="handleLogoUploadPreview"
                :on-exceed="handleLogoUploadExceed"
                :on-success="handleLogoUploadSuccess"
              >
                <el-button>浏览上传附件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    允许上传的文件类型：.doc, .docx, .xls, .xlsx, .pdf, .zip,
                    .rar，最多允许上传5个文件，单个文件不超过 20M
                  </div>
                </template>
              </el-upload>
            </div>
          </el-row>
        </el-main>

        <el-aside
          style="border-left: 1px solid #efefef; padding-left: 20px"
          width="350px"
        >
          <el-row>
            <el-col>
              <el-form-item
                :label="t('article.channelName')"
                prop="channelLevelCode"
              >
                <el-tree-select
                  ref="channelRef"
                  v-model="formEdit.channelLevelCode"
                  :data="state.channelList"
                  :render-after-expand="false"
                  @current-change="handleChannelChange"
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item prop="publicationDate">
                <template #label>
                  {{ t("article.publicationDate") }}
                  <el-popover
                    placement="top"
                    :width="200"
                    effect="dark"
                    :content="t('article.publicationDateContent')"
                  >
                    <template #reference>
                      <el-icon style="vertical-align: sub; cursor: pointer"
                        ><Warning
                      /></el-icon>
                    </template>
                  </el-popover>
                </template>
                <template #default>
                  <el-date-picker
                    v-model="state.publicationDate"
                    type="datetime"
                    class="fix-el-date-picker-width"
                    style="width: 100%"
                  />
                </template>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('article.sourceName')">
                <el-input
                  v-model="formEdit.sourceName"
                  maxlength="32"
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('article.sourceUrl')">
                <el-input
                  v-model="formEdit.sourceUrl"
                  maxlength="128"
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('article.author')">
                <el-input v-model="formEdit.author" maxlength="32" clearable>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item
                :label="t('article.listLayoutImage')"
                prop="listLayout"
              >
                <el-select
                  v-model="formEdit.listLayout"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="只有标题文字" :value="0"></el-option>
                  <el-option
                    label="标题在左侧，一个图片在右侧"
                    :value="1"
                  ></el-option>
                  <el-option
                    label="标题在上面，一个图片充满"
                    :value="2"
                  ></el-option>
                  <el-option
                    label="标题在上面，三个图片并列在下面"
                    :value="3"
                  ></el-option>
                </el-select>
                <el-skeleton
                  style="width: 325px"
                  v-if="formEdit.listLayout == 0"
                >
                  <template #template>
                    <el-skeleton-item variant="text" style="width: 100%" />
                  </template>
                </el-skeleton>
                <el-skeleton
                  style="
                    width: 325px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                  "
                  v-if="formEdit.listLayout == 1"
                >
                  <template #template>
                    <div style="width: 200px; display: block">
                      <el-skeleton-item variant="text" style="width: 100%" />
                      <el-skeleton-item variant="text" style="width: 100%" />
                      <el-skeleton-item variant="text" style="width: 80%" />
                    </div>
                    <el-skeleton-item
                      v-if="formEdit.listImage0FileId == ''"
                      variant="image"
                      style="width: 105px; height: 70px; cursor: pointer"
                      @click="handleUploadListImage(1, 'listImage0FileId')"
                    />
                    <el-image
                      v-if="formEdit.listImage0FileId != ''"
                      style="width: 105px; height: 70px; cursor: pointer"
                      :src="apiUpload.downloadUrl(formEdit.listImage0FileId)"
                      @click="handleUploadListImage(1, 'listImage0FileId')"
                      fit="cover"
                    />
                  </template>
                </el-skeleton>
                <el-skeleton
                  style="width: 325px"
                  v-if="formEdit.listLayout == 2"
                >
                  <template #template>
                    <div style="width: 325px; display: block">
                      <el-skeleton-item variant="text" style="width: 100%" />
                    </div>
                    <el-skeleton-item
                      v-if="formEdit.listImage0FileId == ''"
                      variant="image"
                      style="width: 325px; height: 156px; cursor: pointer"
                      @click="handleUploadListImage(2, 'listImage0FileId')"
                    />
                    <el-image
                      v-if="formEdit.listImage0FileId != ''"
                      style="width: 325px; height: 156px; cursor: pointer"
                      :src="apiUpload.downloadUrl(formEdit.listImage0FileId)"
                      @click="handleUploadListImage(2, 'listImage0FileId')"
                      fit="cover"
                    />
                  </template>
                </el-skeleton>
                <el-skeleton
                  style="width: 325px"
                  v-if="formEdit.listLayout == 3"
                >
                  <template #template>
                    <div style="width: 325px; display: block">
                      <el-skeleton-item variant="text" style="width: 100%" />
                    </div>
                    <div
                      style="
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                      "
                    >
                      <el-skeleton-item
                        v-if="formEdit.listImage0FileId == ''"
                        variant="image"
                        style="width: 105px; height: 70px; cursor: pointer"
                        @click="handleUploadListImage(3, 'listImage0FileId')"
                      />
                      <el-image
                        v-if="formEdit.listImage0FileId != ''"
                        style="width: 105px; height: 70px; cursor: pointer"
                        :src="apiUpload.downloadUrl(formEdit.listImage0FileId)"
                        @click="handleUploadListImage(3, 'listImage0FileId')"
                        fit="cover"
                      />
                      <el-skeleton-item
                        v-if="formEdit.listImage1FileId == ''"
                        variant="image"
                        style="width: 105px; height: 70px; cursor: pointer"
                        @click="handleUploadListImage(3, 'listImage1FileId')"
                      />
                      <el-image
                        v-if="formEdit.listImage1FileId != ''"
                        style="width: 105px; height: 70px; cursor: pointer"
                        :src="apiUpload.downloadUrl(formEdit.listImage1FileId)"
                        @click="handleUploadListImage(3, 'listImage1FileId')"
                        fit="cover"
                      />
                      <el-skeleton-item
                        v-if="formEdit.listImage2FileId == ''"
                        variant="image"
                        style="width: 105px; height: 70px; cursor: pointer"
                        @click="handleUploadListImage(3, 'listImage2FileId')"
                      />
                      <el-image
                        v-if="formEdit.listImage2FileId != ''"
                        style="width: 105px; height: 70px; cursor: pointer"
                        :src="apiUpload.downloadUrl(formEdit.listImage2FileId)"
                        @click="handleUploadListImage(3, 'listImage2FileId')"
                        fit="cover"
                      />
                    </div>
                  </template>
                </el-skeleton>
              </el-form-item>
            </el-col>

            <el-col>
              <el-form-item :label="t('article.tags')">
                <el-space :wrap="true" :size="10" alignment="left">
                  <el-tag
                    v-for="tag in dynamicTags"
                    :key="tag"
                    class="mx-1"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="inputVisible"
                    ref="InputRef"
                    v-model="inputValue"
                    class="ml-1 w-20"
                    size="small"
                    @keyup.enter="handleInputConfirm"
                    @blur="handleInputConfirm"
                  />
                  <el-button
                    v-else
                    class="button-new-tag ml-1"
                    size="small"
                    @click="showInput"
                  >
                    {{ t("article.newTag") }}
                  </el-button>
                </el-space>
                <!-- 标签库 -->
                <div
                  style="
                    border-top: 1px dashed #ddd;
                    width: 100%;
                    margin-top: 10px;
                    padding-top: 10px;
                  "
                >
                  <el-space :wrap="true" :size="10" alignment="left">
                    <el-tag
                      v-for="tag in state.taglList"
                      :key="tag.tagId"
                      type="info"
                      style="cursor: pointer"
                      class="mx-1"
                      :disable-transitions="false"
                      @click="handleAddTag(tag.tagName)"
                    >
                      {{ tag.tagName }}
                    </el-tag>
                    <el-button
                      class="button-new-tag ml-1"
                      size="small"
                      v-if="state.tagMore"
                      @click="handleQueryTag"
                    >
                      + More
                    </el-button>
                  </el-space>
                </div>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('article.topIndex')">
                <el-switch
                  v-model="formEdit.top"
                  :active-value="true"
                  :inactive-value="false"
                />
                <el-input-number
                  v-model="formEdit.topIndex"
                  :controls="false"
                  :disabled="!formEdit.top"
                  max="10"
                  min="0"
                  class="el-input-number-left-fix"
                  style="margin-left: 20px; width: 60px"
                  placeholder="排序"
                  clearable
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('article.description')">
                <el-input
                  v-model="formEdit.description"
                  type="textarea"
                  maxlength="64"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-aside>
      </el-container>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-affix position="bottom" :offset="20">
          <el-button @click="state.dialogFormVisible = false">{{
            t("common.cancelButton")
          }}</el-button>
          <el-button @click="handleSubmit(0)">{{
            t("common.draftButton")
          }}</el-button>
          <el-button @click="handleSubmit(2)">{{
            t("common.draftPreviewButton")
          }}</el-button>
          <el-button type="primary" @click="handleSubmit(1)">{{
            t("common.publishButton")
          }}</el-button>
        </el-affix>
      </span>
    </template>
  </el-dialog>
  <list-image
    ref="listImageRef"
    @on-submit-success="onListImageUpload"
  ></list-image>
</template>

<script setup lang="ts">
import {
  reactive,
  ref,
  toRefs,
  toRaw,
  watch,
  nextTick,
  onUnmounted,
} from "vue";
import { ElInput } from "element-plus";
import { Warning } from "@element-plus/icons-vue";
import { useStore } from "../../../stores/store";
import utils from "../../../utils/utils";
import moment from "moment";
import { Plus } from "@element-plus/icons-vue";
import { headers } from "../../../utils/request";
import apiUpload from "../../admin/api/upload";
import apiCms from "../api/cms";
import listImage from "./list-image.vue";
import DecoupledEditor from "@ckeditor/ckeditor5-build-decoupled-document";
import "@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn";

const env = import.meta.env;
import { useI18n } from "vue-i18n";
import axios from "axios";
const { t } = useI18n({ useScope: "global" });
const emit = defineEmits<{
  (event: "on-submit-success", row: any): void;
}>();

const store = useStore();
const formRef = ref();
const channelRef = ref();
const listImageRef = ref();

const logoFileRef = ref();
const logoFileCategory = "cms-attach-file";
const logoFileList = ref([]);

const stateOriginal = () =>
  reactive({
    dialogFormVisible: false,
    publicationDate: "",
    channelList: Array<any>(),
    // 标签库
    taglList: Array<any>(),
    tagPage: 1,
    tagMore: true,
    editorData: "",
    editorConfig: {
      // The configuration of the editor.
      language: "zh_CN",
      // ckfinder: {
      //   // 后端处理上传逻辑返回json数据, 包括uploaded 上传的字节数 和url两个字段
      //   uploadUrl: process.env.VUE_APP_BASE_URL + `/upload`,
      // },
    },
  });
const state = reactive(stateOriginal());

const formEditOriginal = () => {
  return {
    articleId: "",
    channelId: "",
    channelName: "",
    channelLevelCode: "",
    title: "",
    listLayout: 0,
    listImageFileIds: "",
    listImage0FileId: "",
    listImage1FileId: "",
    listImage2FileId: "",
    author: "",
    sourceName: "",
    sourceUrl: "",
    publicationDate: "",
    tags: "",
    top: false,
    topIndex: null,
    readCount: 0,
    status: 1,
    description: "",
    content: "",
    // 图片+附件
    fileIds: "",
  };
};
const formEdit = reactive(formEditOriginal());

const rules = reactive({
  channelLevelCode: [
    {
      required: true,
      message: () => t("common.select"),
      trigger: "change",
    },
  ],
  title: [
    { required: true, message: () => t("common.required"), trigger: "blur" },
  ],
  publicationDate: [
    // { required: true, message: () => t("common.select"), trigger: "change" },
    {
      validator: (rule: any, value: any, callback: any) => {
        console.log("publicationDate validator", value);
        // 由于 publicationDate 未绑定到 formEdit 所以 value 取不到值，直接使用 state.publicationDate
        if (state.publicationDate === "" || state.publicationDate === null) {
          callback(new Error(t("common.select")));
        } else {
          callback();
        }
      },
      trigger: "change",
      required: true,
    },
  ],

  listLayout: [
    {
      required: true,
      message: () => t("common.select"),
      trigger: "change",
    },
  ],
});

const handleAffixScroll = (value: { scrollTop: number; fixed: boolean }) => {
  // console.log("handleAffixScroll", value);
  if (value.scrollTop > 300) {
    // 动态移动编辑器工具栏
    var toolbar = document.getElementById("toolbar-container");
    var affixContainer = document.getElementById("affix-container").children[0];
    affixContainer.appendChild(toolbar);
  } else {
    var toolbar = document.getElementById("toolbar-container");
    var toolbarContainer = document.getElementById("affix-reset-container");
    toolbarContainer.appendChild(toolbar);
  }
};

const handleLogoUploadPreview = (file: any) => {
  window.open(apiUpload.downloadUrl(file.uid));
};
const handleLogoUploadExceed = (files: any) => {
  // 超过限制数量自动替换旧文件
  console.log("handleLogoUploadExceed", files);
  // logoFileRef.value!.clearFiles();
};
const handleLogoUploadSuccess = (
  response: any,
  uploadFile: any,
  uploadFiles: any
) => {
  if (response.code == 200) {
    // 更新服务器端主键
    uploadFile.uid = response.data.fileId;
    // 如果没有输入标题，用文件名替换
    if (formEdit.title == "") {
      formEdit.title = response.data.fileName;
    }
  }
};

const handleChannelChange = (currentNode: any, prevNode: any) => {
  // console.log(currentNode, currentNode.label);
  const node = channelRef.value.getCurrentNode();
  if (node != null && node.children.length == 0) {
    // console.log("子节点", node.label);
    // 子节点
    formEdit.channelId = node.channelId;
    formEdit.channelName = node.label;
  }
};

//#region tags
const inputValue = ref("");
const dynamicTags = ref([]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};
const handleInputConfirm = () => {
  let tag = inputValue.value;
  tag = utils.replaceAll(tag, ",", "");
  if (tag) {
    dynamicTags.value.push(tag);
  }
  inputVisible.value = false;
  inputValue.value = "";
};
// 加载标签库数据
const handleQueryTag = () => {
  const pageSize = 10;
  const params = {
    // 当前页码
    page: state.tagPage,
    // 每页数量，不分页的情况限制最大请求 9999 条数据
    rows: pageSize,
    sort: "tagCount",
    order: "ascending",
  };

  let data = { rows: [], total: 0 };
  apiCms
    .queryTagListing(params)
    .then((response: any) => {
      data = response.data;
      data.rows.forEach((m) => {
        state.taglList.push(m);
      });
      if (data.rows.length == pageSize) {
        state.tagPage++;
      } else {
        // 隐藏加载更多按钮
        state.tagMore = false;
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};
// 从标签库选择标签添加
const handleAddTag = (tagName: string) => {
  let exists = false;
  dynamicTags.value.forEach((m) => {
    if (m == tagName) {
      exists = true;
    }
  });
  if (!exists) {
    dynamicTags.value.push(tagName);
  }
};
//#endregion

//#region upload list image
const listImageFileRef = ref();
const listImageFileCategory = "cms-list-image";
const listImageFileList = ref([]);

const handleListImageFileBeforeUpload = (file: any) => {
  if (file.type.indexOf("image/") == -1) {
    // console.log("handleListImageFileBeforeUpload", file, listImageFileList.value);
    // utils.infoNotification(t("common.submitSuccess"));
    utils.infoNotification(t("upload.imgType"));
    return false;
  }
  // console.log("file.size", file.size);
  // byte
  if (file.size / 1024 < 100) {
    // 上传图片应小于100K，请重新上传
    utils.infoNotification(t("upload.fileSizeGreater", { size: 100 }));
    return false;
  } else if (file.size / 1024 / 1024 > 5) {
    utils.infoNotification(t("upload.fileSizeLessMB", { size: 5 }));
    return false;
  }
};
const handleListImageFileUploadPreview = (file: any) => {
  // todo 统一预览页面
  // console.log("handleListImageFileUploadPreview", file);
  window.open(apiUpload.downloadUrl(file.uid));
};
const handleListImageFileUploadExceed = (files: any) => {
  utils.infoNotification(t("upload.exceeds", { number: 3 }));
};
const handleListImageFileUploadSuccess = (
  response: any,
  uploadFile: any,
  uploadFiles: any
) => {
  if (response.code == 200) {
    // 更新服务器端主键
    uploadFile.uid = response.data.fileId;
  }
  //uploadFile: {uid:1234, name:"xxx", size:1234, url:"xxx",raw:{}, response:{}}
  // console.log("handleListImageFileUploadSuccess response", response);
  // console.log("handleListImageFileUploadSuccess uploadFile", uploadFile);
  // console.log("handleListImageFileUploadSuccess uploadFiles", uploadFiles);
};
const handleUploadListImage = (layout: number, sender: string) => {
  // console.log("handleUploadListImage", sender);
  let fileId = null;
  if (sender == "listImage0FileId") {
    fileId = formEdit.listImage0FileId;
  } else if (sender == "listImage1FileId") {
    fileId = formEdit.listImage1FileId;
  } else if (sender == "listImage2FileId") {
    fileId = formEdit.listImage2FileId;
  }
  listImageRef.value.show(layout, formEdit.articleId, sender, fileId);
};
const onListImageUpload = (sender: string, fileId: string) => {
  // console.log("onListImageUpload", sender, fileId);
  if (sender == "listImage0FileId") {
    formEdit.listImage0FileId = fileId;
  } else if (sender == "listImage1FileId") {
    formEdit.listImage1FileId = fileId;
  } else if (sender == "listImage2FileId") {
    formEdit.listImage2FileId = fileId;
  }
  state.channelList.push({ uid: fileId });
};
//#endregion

//#region editor
// https://ckeditor.com/docs/ckeditor5/latest/installation/integrations/vuejs-v3.html
// Integrating a build from the online builder

let ckeditor = null as any;
class MyUploadAdapter {
  loader = null;
  constructor(loader) {
    this.loader = loader;
  }

  async upload() {
    const data = new FormData();
    data.append("file", await this.loader.file);
    data.append("category", "cms-detail-image");
    data.append("businessKey", formEdit.articleId);
    const res = await axios({
      url: apiUpload.uploadUrl(),
      method: "POST",
      data,
      withCredentials: false, // true 为不允许带 token, false 为允许
      headers: headers(),
    });

    console.log(res.data);
    return {
      default: apiUpload.editorUrl(res.data.data.fileId),
    };
  }
}

const initCKEditor = (html) => {
  // https://ckeditor.com/docs/ckeditor5/latest/examples/builds/classic-editor.html
  // DecoupledEditor.defaultConfig = {};
  // export default class ClassicEditor extends ClassicEditorBase {}
  const editorPlaceholder = document.querySelector("#editor") as HTMLElement;
  DecoupledEditor.create(editorPlaceholder, {
    // removePlugins: [ 'Heading' ],
    // plugins: [],
    language: "zh-cn",
    toolbar: {
      items: [
        "heading",
        "|",
        // "fontsize",
        // "fontfamily",
        // "|",
        "bold",
        "italic",
        "underline",
        "strikethrough",
        "highlight",
        "|",
        "alignment",
        "|",
        "numberedList",
        "bulletedList",

        "|",
        "comment",
        "commentsArchive",
        "trackChanges",
        "|",
        "mediaEmbed",
        "imageUpload",
        "link",
        "blockquote",
        "insertTable",
        "|",
        "undo",
        "redo",
      ],
    },
    // https://ckeditor.com/docs/ckeditor5/latest/features/headings.html#configuring-custom-heading-elements
    heading: {
      options: [
        {
          model: "paragraph",
          title: "正文",
          class: "ck-heading_paragraph",
        },
        {
          model: "heading2",
          view: "h2",
          title: "一级标题",
          class: "",
        },
        {
          model: "heading3",
          view: "h3",
          title: "二级标题",
          class: "",
        },
        {
          model: "heading4",
          view: "h4",
          title: "三级标题",
          class: "",
        },
      ],
    },
    image: {
      resizeUnit: "px",
      resizeOptions: [
        {
          name: "resizeImage:original",
          value: null,
          icon: "original",
        },
        {
          name: "resizeImage:medium",
          value: "500",
          icon: "medium",
        },
        {
          name: "resizeImage:large",
          value: "700",
          icon: "large",
        },
      ],
      toolbar: [
        "imageTextAlternative",
        "toggleImageCaption",
        "|",
        // "imageStyle:inline",
        "imageStyle:wrapText",
        "imageStyle:breakText",
        // "imageStyle:side",
        "|",
        "resizeImage:medium",
        "resizeImage:large",
        "resizeImage:original",
      ],
    },
    table: {
      contentToolbar: ["tableColumn", "tableRow", "mergeTableCells"],
      tableToolbar: ["comment"],
    },
    mediaEmbed: {
      toolbar: ["comment"],
    },
  })
    .then((newEditor) => {
      const toolbarContainer = document.querySelector("#toolbar-container");
      toolbarContainer.appendChild(newEditor.ui.view.toolbar.element);
      // console.log("newEditor.plugins", newEditor.plugins);
      newEditor.plugins.get("FileRepository").createUploadAdapter = (
        loader
      ) => {
        return new MyUploadAdapter(loader);
      };

      newEditor.setData(html);
      ckeditor = newEditor;
    })
    .catch((error) => {
      console.error("initCKEditor", error);
    });
};
//#endregion

const handleSubmit = async (action: number) => {
  await formRef.value.validate();

  // console.log("handleSubmit", typeof state.publicationDate, state.publicationDate == "");

  if (formEdit.top && formEdit.topIndex == null) {
    utils.infoNotification(t("article.topIndexNeed"));
    return;
  }

  // 第一次 ""，后续修改为 object
  if (state.publicationDate == "" || state.publicationDate == null) {
    // formEdit.birthday = moment().format("YYYY-MM-DD");
    formEdit.publicationDate = "";
  } else if (typeof state.publicationDate == "object") {
    formEdit.publicationDate = moment(state.publicationDate).format(
      "YYYY-MM-DD HH:mm:ss"
    );
  }

  // state.channelList.forEach((m) => {
  //   if (m.channelId == formEdit.channelId) {
  //     formEdit.channelName = m.name;
  //   }
  // });

  formEdit.tags = "";
  dynamicTags.value.forEach((m) => {
    formEdit.tags += m + ",";
  });
  if (formEdit.tags.length > 0) {
    formEdit.tags = formEdit.tags.substring(0, formEdit.tags.length - 1);
  }

  let fileIds = "";
  // listImageFileList.value.forEach((file) => {
  //   fileIds += file.uid + ",";
  // });
  if (formEdit.listLayout == 1 || formEdit.listLayout == 2) {
    // 布局1、2
    if (formEdit.listImage0FileId == "") {
      utils.infoNotification(t("article.uploadListImage"));
      return;
    }
    fileIds = formEdit.listImage0FileId;
  } else if (formEdit.listLayout == 3) {
    // 布局3
    if (
      formEdit.listImage0FileId == "" ||
      formEdit.listImage1FileId == "" ||
      formEdit.listImage2FileId == ""
    ) {
      utils.infoNotification(t("article.uploadListImage"));
      return;
    }
    fileIds =
      formEdit.listImage0FileId +
      "," +
      formEdit.listImage1FileId +
      "," +
      formEdit.listImage2FileId;
  }

  formEdit.listImageFileIds = fileIds;

  // 附件
  logoFileList.value.forEach((file) => {
    fileIds += "," + file.uid;
  });
  formEdit.fileIds = fileIds;

  // let html = ckeditorRef.value.getData();
  // formEdit.content = html;

  let html = ckeditor.getData();
  formEdit.content = utils.base64Encode(html);

  if (formEdit.top == false) {
    formEdit.topIndex = 0;
  }

  formEdit.status = action;
  if (action == 2) {
    // 保存草稿并预览
    formEdit.status = 0;
  }

  // 处理业务逻辑，触发关闭事件
  apiCms
    .saveArticle(formEdit)
    .then((response: any) => {
      if (response.data.code == 200) {
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit);
        if (action == 2) {
          // 保存草稿并预览
          const url = env.VITE_API_CMS_PREVIEW_PATH.replace(
            "{articleId}",
            formEdit.articleId
          ).replace("{channelLevelCode}", formEdit.channelLevelCode);
          window.open(url);
        }
        if (action == 1) {
          state.dialogFormVisible = false;
        }
      }
    })
    .catch((err: any) => {
      // 还原原文
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = (row: any) => {
  // tags
  inputValue.value = "";
  dynamicTags.value = [];
  inputVisible.value = false;

  state.publicationDate = moment().format("YYYY-MM-DD HH:mm:ss");
  state.taglList = Array<any>();
  state.tagPage = 1;
  state.tagMore = true;

  logoFileList.value = [];

  apiCms
    .loadChannelJson()
    .then((response: any) => {
      if (response.data.code == 200) {
        Object.assign(state.channelList, response.data.data);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });

  Object.assign(formEdit, formEditOriginal());
  if (row != undefined) {
    apiCms
      .getArticle(row.articleId)
      .then((response: any) => {
        if (response.data.code == 200) {
          Object.assign(formEdit, response.data.data);
          if (formEdit.tags.length > 0) {
            dynamicTags.value = formEdit.tags.split(",");
          }
          if (
            (formEdit.listLayout == 1 || formEdit.listLayout == 2) &&
            formEdit.listImageFileIds.length > 0
          ) {
            formEdit.listImage0FileId = formEdit.listImageFileIds;
          } else if (
            formEdit.listLayout == 3 &&
            formEdit.listImageFileIds.length > 0
          ) {
            let ids = formEdit.listImageFileIds.split(",");
            formEdit.listImage0FileId = ids[0];
            formEdit.listImage1FileId = ids[1];
            formEdit.listImage2FileId = ids[2];
          }

          response.data.attachFiles.forEach((file) => {
            logoFileList.value.push({
              uid: file.fileId,
              name: file.fileName,
              url: apiUpload.downloadUrl(file.fileId),
            });
          });

          state.publicationDate = formEdit.publicationDate;
          // console.log("state.publicationDate", formEdit.publicationDate);

          if (formEdit.topIndex > 0) {
            formEdit.top = true;
          } else {
            formEdit.topIndex = null;
          }

          setTimeout(() => {
            initCKEditor(response.data.content.content);
          }, 500);
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  } else {
    // 初始化id
    apiCms
      .generateId()
      .then((response: any) => {
        if (response.data.code == 200) {
          formEdit.articleId = response.data.data;
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });

    setTimeout(() => {
      initCKEditor("");
    }, 1000);
  }

  handleQueryTag();

  state.dialogFormVisible = true;
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 强制立即执行侦听，组件启动就获取一次值
const unwatch = watch(
  () => formEdit.top,
  (newValue, oldValue) => {
    if (newValue == false) {
      formEdit.topIndex = null;
    }
  },
  { deep: true, immediate: true }
);

onUnmounted(() => {
  unwatch();
});

const onDialogClose = () => {
  if (ckeditor) {
    ckeditor.destroy();
  }
};

defineExpose({
  show,
});
</script>
<style lang="scss">
#affix-container {
  background-color: aliceblue;
  width: 10px;
}
#affix-container:first-child {
  background-color: bisque;
}

#editor {
  display: block;
  min-height: 780px;
  width: 750px;
  .table {
    display: table;
    min-width: 400px;
    margin: 0.9em auto;
    table {
      border: 1px double #b3b3b3;
      border-collapse: collapse;
      border-spacing: 0;
      height: 100%;
      width: 100%;
    }
  }
}
.ck-editor__editable {
  // min-height: 780px;
  // width: 750px;
  // border: 1px solid #4878e3 !important;
  border-radius: 2px;
  box-shadow: 2px 2px 3px var(--ck-color-shadow-inner) inset, 0 0;

  p {
    overflow-wrap: break-word;
    word-wrap: break-word;
    font-size: 18px;
    color: rgb(51, 51, 51);
    line-height: 34px;
    margin-bottom: 30px;
  }

  font: 400 1em/1.8 "PingFang SC", "Microsoft Yahei", "Avenir", "Segoe UI",
    "Hiragino Sans GB", "STHeiti", "Microsoft Sans Serif", "WenQuanYi Micro Hei",
    sans-serif;
}
.ck-powered-by {
  display: none;
}
.ck-body-wrapper {
  z-index: 1300 !important;
}
</style>
